package com.hub.videobrowsdownload

import android.content.Context
import android.util.Log
import android.webkit.WebView
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.math.BigDecimal
import java.util.Locale


object BrowsM3U8Helper {

    var useM3U8FakeContentLength = true

    fun getDownloadFileParentDir(context:Context, id:Long) :File{
        val sp = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
        var dir = File(context.filesDir, "video_download");
        if (sp.getBoolean("use_external", false)) {
            val externalFilesDirs = context.getExternalFilesDirs("video_download")
            if (!externalFilesDirs.isNullOrEmpty()) {
                dir = externalFilesDirs.last()
            }
        }

        val childDir = File(dir, id.toString())
        if (!childDir.exists()) {
            childDir.mkdirs()
        }
        return childDir
    }
      fun copyFile(sourceFile: File, destinationFile: File): Boolean {
        try {
            if (!destinationFile.exists()) {
                destinationFile.createNewFile()
            }
            sourceFile.inputStream().use { input ->
                destinationFile.outputStream().use { output ->
                    input.copyTo(output)
                }
            }
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }
    fun getThumbDir(context:Context):File {
        val file = File(context.filesDir, "video_thumb")
        if (!file.exists()) {
            file.mkdirs()
        }
        return file
    }
    fun tickShowHtmlVideo(webView :WebView) {
        if (!webView.getUrl()
                .isNullOrEmpty() && webView.getProgress() > 90
        ) {
            webView.evaluateJavascript(
                "javascript:window.VideoInfoJSI.showVideoHTML( function() { var length = document.getElementsByTagName(\'video\').length;var arr = new Array(length);for(var i = 0; i < length; i++){arr[i] = document.getElementsByTagName(\'video\')[i].outerHTML;}return arr; }());",
                null
            )
        }
    }
    fun findM3U8Video(src: String, tabWebViewModel: BrowsTabWebViewModel) {
        tabWebViewModel.findM3U8Video(src)
    }

    fun findMP4Video(src: String, tabWebViewModel: BrowsTabWebViewModel) {
        tabWebViewModel.findMP4Video(src)
    }
    fun getUrlParent(s:String):String {
        var parentUrl = s
        if (s.contains("?")) {
            parentUrl = s.substring(0, s.lastIndexOf("?"))
        }
        val index = parentUrl.lastIndexOf("/")
        if (index > 9) {
            parentUrl = parentUrl.substring(0, index)
        }
        return parentUrl
    }
    fun getUrlPath(s: String): String {
        val v = s.indexOf(0x3F.toChar())
        val v1 = s.lastIndexOf(0x2F.toChar())
        if (v == -1) {
            return s.substring(v1 + 1).lowercase(Locale.getDefault())
        }
        return if (v1 >= v) s.substring(s.substring(0, v).lastIndexOf(0x2F.toChar()) + 1, v)
            .lowercase(
                Locale.getDefault()
            ) else s.substring(v1 + 1, v).lowercase(Locale.getDefault())
    }
    @Throws(IOException::class)
    fun checkM3U8isGood(file0: File?): Boolean {
        val fileReader0 = FileReader(file0)
        val bufferedReader0 = BufferedReader(fileReader0)
        val s = bufferedReader0.readLine()
        fileReader0.close()
        bufferedReader0.close()
        return s != null && s.startsWith("#EXTM3U")
    }
    @Throws(IOException::class)
    fun checkM3U8isSteamInf(file0: File?): Boolean {
        val fileReader0 = FileReader(file0)
        val bufferedReader0 = BufferedReader(fileReader0)
        var isO = false
        do {
            val s = bufferedReader0.readLine()
            if (s.isNullOrEmpty()) {
                break
            }else{
                if (s.startsWith("#EXT-X-STREAM-INF:")) {
                   isO = true
                    break
                }else if (s.startsWith("#EXT-X-MAP:URI=")) {
                    isO = true
                    break
                }
            }
        } while (true)
        bufferedReader0.close()
        fileReader0.close()
        return isO
    }
     fun findVideoSrc(src: String?, tabWebViewModel: BrowsTabWebViewModel) {
        if (src.isNullOrEmpty()) {
            return
        }
        var realSrc = ""
        if (!src.startsWith("/") && !src.startsWith("../")) {
            if (src.startsWith("https://") || src.startsWith("http://")) {
                realSrc = src;
            } else {
                return;
            }
        } else {
            val host = tabWebViewModel.currentWebUrl.value!!.substring(0, tabWebViewModel.currentWebUrl.value!!.indexOf("/", 9));
            var videoSrcShame = ""
            if (src.startsWith("/")) {
                videoSrcShame = src.substring(1);
            } else if (src.startsWith("../")) {
                videoSrcShame = src.substring(3);
            }

            realSrc = "$host/$videoSrcShame"
        }
        val urlPath = getUrlPath(realSrc)
        if (urlPath.endsWith(".m3u8")) {
            val v = realSrc.indexOf(".m3u8") + 5
            val hashCode =
                BrowsHash256.toHash(if (v == realSrc.length) realSrc else realSrc.substring(0, v))
            // .m3u8 有些网站需要解密

            // TODO: GET M3U8 URL
            findM3U8Video(realSrc, tabWebViewModel)
            return
        }
        if (!urlPath.endsWith(".mp4") && !urlPath.endsWith(".ogg") && !urlPath.endsWith(".webm")) {
            Log.d("tabf", "executeUrls: else");
            return;
        }

        var v2 = 0
        val z: Boolean = tabWebViewModel.currentWebUrl.value!!.contains(".instagram.")
        var v1 = realSrc.indexOf(".mp4")
        if (v1 == -1) {
            v1 = realSrc.indexOf(".ogg")
            v2 = if (v1 == -1) realSrc.indexOf(".webm") + 5 else v1 + 4
        } else {
            v2 = v1 + 4
        }
        val hashCode =
            BrowsHash256.toHash(if (v2 == realSrc.length) realSrc else realSrc.substring(0, v2))
        Log.i("src_mp4", realSrc)
        // TODO: GET MP4 URL
        findMP4Video(realSrc, tabWebViewModel)
    }

    fun formatFileSize(size: Double): String {
        if (size < 0) {
            return "0k"
        }
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            return size.toString() + "b"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(kiloByte.toString())
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "k"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(megaByte.toString())
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "m"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(gigaByte.toString())
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "g"
        }
        val result4 = BigDecimal(teraBytes)
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "t"
    }
}